<template>
  <div class="comments-container">
    <h3>发表评论</h3>
    <textarea rows="4" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="postCommnent">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item, i) in commentList" :key="item.add_time">
        <div
          class="cmt-title"
        >第{{ i+1 }}楼 &nbsp;&nbsp; 用户名：{{ item.username }}&nbsp;&nbsp;发表时间：{{ item.add_time | dateFromt }}</div>
        <div class="cmt-content">{{ item.content }}</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getList">加载更多</mt-button>
  </div>
</template>
<script>
import Toast from "mint-ui";
export default {
  data() {
    return {
      commentList: [],
      pageindex: 1,
      msg: ""
    };
  },
  props: ["id"],
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      this.$http
        .get("api/getcomments/" + this.id + "%20?pageindex=" + this.pageindex)
        .then(result => {
          if (result.data.status == 0) {
            this.commentList = this.commentList.concat(result.data.message);
          }
        });
    },
    getList() {
      this.pageindex++;
      this.getComments();
    },
    postCommnent() {
      if (this.msg.trim().length == 0) {
        return Toast("评论内容不能为空！！");
      }
      this.$http
        .post("api/postcomment/" + this.$route.params.id, {
          content: this.msg.trim()
        })
        .then(result => {
          if (result.data.status == 0) {
            this.commentList.unshift({
              add_time: Date.now(),
              content: this.msg,
              user_name: "匿名用户"
            });
            this.msg = "";
          }
        });
    }
  }
};
</script>
<style lang="scss" scope>
.comments-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    margin: 0;
  }
  .cmt-list {
    .cmt-item {
      margin-top: 5px;
      .cmt-title {
        font-size: 13px;
        margin: 5px 0;
        padding: 5px;
        background-color: #ccc;
      }
      .cmt-content {
        margin: 10px 0;
        text-indent: 2em;
      }
    }
  }
}
</style>